// pages/todoOrder/todoOrder.js
var config = require('../../script/config');
var orderApi = require('../../script/order.js');
// var QQMapWX = require('../../qqmap/qqmap-wx-jssdk');
// var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IsNear: 1, // 1全部 2 附近工单
    userinfo: null,
    activeIndex: 1,
    HandleCount: 0,
    ExpireCount: 0,
    ReminderCount: 0,
    UrgencyCount: 0,
    pagination: {
      page: 1,
      rows: 4,
      sidx: '',
      sord: ''
    },
    count: 0,
    orderList: [],
    canLoadData: true,
    noData: false,
    isReachBottom: false,
    XiaoQuList: [] // 附近小区
  },
  _refreshData: function () {
    this.setData({ //初始化数据
      // activeIndex: 1,
      HandleCount: 0,
      ExpireCount: 0,
      ReminderCount: 0,
      UrgencyCount: 0,
      pagination: {
        page: 1,
        rows: 4,
        sidx: '',
        sord: ''
      },
      count: 0,
      // orderList: [],
      canLoadData: true,
      noData: false,
      isReachBottom: false,
      XiaoQuList: []
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // qqmapsdk = new QQMapWX({
    //   key: config.mapKey
    // });
    // var IsNear = wx.getStorageSync('IsNear')
    // this.setData({
    //   IsNear: IsNear
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getUserInfo()
    this._refreshData();
    // var IsNear = wx.getStorageSync('IsNear') ? wx.getStorageSync('IsNear') : 1
    // this.setData({
    //   IsNear: IsNear
    // })
    // if (IsNear === 1) {
    //   this.getOrderStatusCount()
    //   this.getOrderList(true)
    // } else {
    //   this.getNearOrderList()
    // }
    this.getOrderStatusCount()
    this.getOrderList(true)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this._refreshData();
    if (this.data.IsNear === 2) {
      this.getNearOrderList()
    } else {
      this.getOrderStatusCount()
      this.getOrderList(true)
    }
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      isReachBottom: true
    });
    if (this.data.canLoadData) {
      this.setData({
        'pagination.page': this.data.pagination.page + 1
      })
      this.getOrderList();
    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 1000
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  searchFocus: function (e) {
    wx.navigateTo({
      url: "../search/search?status=3"
    })
  },
  call: function (e) {
    var pnonenum = e.currentTarget.dataset.phone
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: pnonenum
      });
    } else {
      wx.showActionSheet({
        itemList: [pnonenum, '呼叫'],
        success: function (res) {
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: pnonenum
            })
          }
        }
      })
    }
  },
  // toMap(e) {
  //   var info = e.currentTarget.dataset.info
  //   qqmapsdk.geocoder({
  //     // address: '北京市海淀区彩和坊路海淀西大街74号',
  //     address: info.Address,
  //     success: function (res) {
  //       var res = res.result;
  //       var latitude = res.location.lat;
  //       var longitude = res.location.lng;
  //       wx.openLocation({
  //         latitude: latitude,
  //         longitude: longitude,
  //         // address: '北京市海淀区彩和坊路海淀西大街74号',
  //         address: info.Address,
  //         scale: 18
  //       })
  //     },
  //     fail: function (error) {
  //       console.error(error);
  //     },
  //     complete: function (res) {
  //       console.log(res);
  //     }
  //   })
  //   // wx.getLocation({
  //   //   type: 'gcj02', //返回可以用于 wx.openLocation 的经纬度
  //   //   success(res) {
  //   //     const latitude = res.latitude
  //   //     const longitude = res.longitude
  //   //     wx.openLocation({
  //   //       latitude,
  //   //       longitude,
  //   //       address: info.Address,
  //   //       scale: 18
  //   //     })
  //   //   }
  //   // })
  // },
  tabClick: function (e) {
    this.setData({
      activeIndex: parseInt(e.currentTarget.dataset.index),
      'pagination.page': 1,
      orderList: [],
      canLoadData: true
    })
    this.getOrderList(true);
  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  getOrderList(isRefresh) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let params = {
      pagination: this.data.pagination,
      queryParam: {
        WxStatus: "3", //微信工单状态 1-待分派 2-待接收 3-待执行 31-待执行的二次派单 32-待执行的催办 33-超时 34-紧急
        IsFinish: false,
        NeedAudit: 0
      }
    };
    if (this.data.activeIndex === 2) {
      params.queryParam.WxStatus = "32"
    } else if (this.data.activeIndex === 3) {
      params.queryParam.WxStatus = "33"
    } else if (this.data.activeIndex === 4) {
      params.queryParam.WxStatus = '34'
    }
    if (this.data.IsNear === 2) {
      params.queryParam.XiaoQuList = this.data.XiaoQuList
    }
    orderApi.GetOrderList(params).then(res => {
      if (res.code === 200) {
        let dataList = []
        if (isRefresh) {
          dataList = [...res.data.Items]
        } else {
          dataList = [...this.data.orderList, ...res.data.Items]
        }
        let canLoadData = res.data.HasNextPages
        const noData = dataList.length === 0
        this.setData({
          orderList: dataList,
          count: res.data.TotalCount,
          canLoadData: canLoadData,
          noData: noData
        })
      }
      wx.hideLoading();
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  getOrderStatusCount() {
    const params = {
      IsFinish: false
    }
    if (this.data.IsNear === 2) {
      params.XiaoQuList = this.data.XiaoQuList
    }
    orderApi.GetWxOrderStatusCount(params).then(res => {
      if (res.code === 200) {
        this.setData({
          HandleCount: res.data.HandleCount,
          ExpireCount: res.data.ExpireCount,
          ReminderCount: res.data.ReminderCount,
          UrgencyCount: res.data.UrgencyCount
        })
      }
    });
  },
  receiveOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showLoading({
      title: '接收中',
      mask: true
    })
    const params = {
      OrderID: order.OrderID,
      ProcedureCode: order.ProcedureCode,
      ProcedureStatus: 2,
      HandleWay: 1,
    }
    http.UpdateOrderProcedure(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        wx.showModal({
          content: '是否去处理工单？',
          success:(res) =>{
            if (res.confirm) {
              wx.navigateTo({
                url: "../do-order/do-order?WorkID=" + order.WorkID
              })
            } else if (res.cancel) {
              this.getOrderStatusCount();
              this.getOrderList(true);
            }
          }
        })
      }
    }).catch(_err => {
      wx.hideLoading();
    });;
  },
  todoOrder: function (e) {
    const WorkID = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "../do-order/do-order?WorkID=" + WorkID
    })
  },
  checkSearchType() {
    const type = this.data.IsNear === 1 ? 2 : 1
    this.setData({
      IsNear: type
    })
    wx.setStorageSync('IsNear', type);
    if (type === 1) {
      this.getOrderStatusCount()
      this.getOrderList(true)
    } else {
      this.getNearOrderList()
    }
  },
  // 获取附近工单以及统计
  getNearOrderList() {
    const _this = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        wx.request({
          method: 'GET',
          url: `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&poitype=120300|120301|120302|120303|120304&key=${config.amapKey}&radius=1000&extensions=all&batch=false&roadlevel=0`,
          success: function (res) {
            if (res.data.status === '1') {
              const pois = res.data.regeocode.pois;
              const list = []
              for (var i = 0; i < pois.length; i++) {
                const type = pois[i].type;
                if(type.indexOf('住宅') > -1 || type.indexOf('社区') > -1){
                  list.push(pois[i].name)
                }
              }
              _this.setData({
                XiaoQuList: list
              })
              _this.getOrderStatusCount();
              _this.getOrderList(true);
            }
            console.log(res.data);
          },
        })
      }
    })
  },
  // getNearOrderList1() {
  //   const _this = this
  //   wx.getLocation({
  //     type: 'gcj02',
  //     success(res) {
  //       const latitude = res.latitude
  //       const longitude = res.longitude
  //       qqmapsdk.search({
  //         keyword: '小区',
  //         location: '' + latitude + ',' + '' + longitude,
  //         distance: 2000,
  //         page_size: 20,
  //         success: function (resp) {
  //           const list = []
  //           for (var i = 0; i < resp.data.length; i++) {
  //             list.push(resp.data[i].title)
  //           }
  //           _this.setData({
  //             XiaoQuList: list
  //           })
  //           _this.getOrderStatusCount();
  //           _this.getOrderList(true);
  //         }
  //       })
  //       // qqmapsdk.reverseGeocoder({
  //       //   location: {
  //       //     latitude: latitude,
  //       //     longitude: longitude
  //       //   },
  //       //   get_poi: 1,
  //       //   success: (res) => {
  //       //     const pois = res.result.pois
  //       //     console.log(pois)
  //       //     _this.getOrderList(true)
  //       //   }
  //       // });
  //     }
  //   })
  // }
})